<?php

namespace app\modules\clinical\models;

use Yii;
use yii\db\Query;

/**
 * This is the model class for table "excel_pdf".
 *
 * @property integer $pk_id
 * @property string $up_time
 * @property string $bf_time
 * @property string $lc_time
 * @property string $dn_time
 * @property string classify
 */
class ExcelPdf extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'excel_pdf';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['up_time', 'bf_time', 'lc_time', 'dn_time'], 'required'],
            [['up_time', 'bf_time', 'lc_time', 'dn_time','sp_time', 'med'], 'safe'],
            [['classify'], 'string', 'max' => 4],
            [['pbm_solve'], 'string', 'max' => 256],
            [['else_ctnt'], 'string', 'max' => 256],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'pk_id' => 'Pk ID',
            'up_time' => '起床时间',
            'bf_time' => '早餐时间',
            'lc_time' => '午餐时间',
            'dn_time' => '晚餐时间',
            'sp_time' => '睡觉时间',
            'classify' => 'H-Y分级',
            'pbm_solve'=> '本次就诊希望解决的问题',
            'else_ctnt'=>'其他用药',
        ];
    }

    public function load($data, $formName = null)
    {
        parent::load($data, $formName);
        if (isset($data['MedCtn'])) {
            $medCtn = $data['MedCtn'];
            $med_array = array();
            foreach ($medCtn as $key => $value) {

                if ($value == 0 || $value == '') continue;

                $add = new \stdClass();
                $add->id = $key;
                $add->value = floatval($value);
                $med_array[] = $add;
            }

            $this->med = json_encode($med_array);
            return true;
        }

        return false;
    }

    public function defaultValue()
    {
        $this->up_time = "06:00";
        $this->bf_time = "07:00";
        $this->lc_time = "11:00";
        $this->dn_time = "18:00";
        $this->sp_time = "22:00";
    }

    public function getMedCtns()
    {
        $result = array();
        if ($this->med != '') {
            $json = $this->med;
            $json = json_decode($this->med);
            foreach ($json as $med) {
                $id = explode('_', $med->id);
                $result[$id[0]][$id[1]] = $med->value;
            }
        }
        return $result;
    }

    public function getMedList($type) {
        $result = (new Query())
            ->select(['pk_id', 'med_name'])
            ->from('med_list')
            ->where(['type' => strtoupper($type)])
            ->all();

        return $result;
    }
}
